/*
 * @lc app=leetcode.cn id=450 lang=javascript
 *
 * [450] 删除二叉搜索树中的节点
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @param {number} key
 * @return {TreeNode}
 */
var getPre = function(root) {
  let node = root.left;
  while(node.right) node = node.right;
  return node;
}

var deleteNode = function(root, key) {
  if(!root) return root;

  if(key > root.val) {
    root.right = deleteNode(root.right, key);
  } else if(key < root.val) {
    root.left = deleteNode(root.left, key);
  } else {
    if(!root.left && !root.right) { //度为0
      delete root;
      return null;
    } else if(!root.left || !root.right) { // 度为1
      const temp = root.left ? root.left : root.right;
      delete root;
      return temp;
    } else { // 度为2
      // 获取前驱节点
      let temp = getPre(root);
      root.val = temp.val;
      root.left = deleteNode(root.left, temp.val);
    }
  }
  return root;
};
// @lc code=end

